﻿using AtomicCms.Common.Models;
using AtomicCms.Data.EntityFramework;
using AtomicCms.Web.Core.ViewModels;

namespace AtomicCms.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Common.Attributes;
    using Common.Entities;
    using Common.Exceptions;
    using Common.Logging;
    using Core;
    using Core.Mvc;
    using Services.Abstract;

    [HandleError]
    [SupportSkin]
    public class HomeController : AtomicCmsController
    {
        private readonly IPageService pageService;
        private readonly ISettingService settingService;
        private readonly ILoggingService log;

        public HomeController(IPageService pageService, ISettingService settingService, ILoggingService log)
        {
            this.pageService = pageService;
            this.settingService = settingService;
            this.log = log;
        }

        public ActionResult Default()
        {
             CmsPage defaultPage = this.pageService.LoadDefault();
            return this.ShowPage(defaultPage);
        }

        [OutputCache(CacheProfile = "Page")]
        public ActionResult Content(int id, string name)
        {
            try
            {
                CmsPage page = this.pageService.Load(id);
                if(page.Alias.ToUpper().Equals(name.ToUpper()))
                {
                    return this.ShowPage(page);
                }
                else
                {
                    log.Warn(string.Format("301 redirect: pageId={0}, alias={1}", id, name));
                    return new LegacyUrl301Result(page.GetUrl());
                }
            }
            catch (PageNotFoundException ex)
            {
                log.Exception(ex);
                return this.PageNotFound();
            }
            catch(Exception ex)
            {
                log.Exception(ex);
                throw;
            }
        }

        private NotFound404Result PageNotFound()
        {
            return new NotFound404Result();
        }

        private ActionResult ShowPage(CmsPage entry)
        {
            return View("Index", entry);
        }



        [OutputCache(CacheProfile = "Page")]
        public PartialViewResult LastPages()
        {
            IEnumerable<CmsPage> lastCreated = this.pageService.LoadLastCreated();
            return PartialView("LastPages",
                               lastCreated);
        }

        public ViewResult Tag(string tag)
        {
            ICollection<Page> matchedPages = pageService.GetPagesWithTag(tag);
            return View(new TagViewModel(){Pages = matchedPages, Tag = tag});
        }
    }
}